package Ep06_BinaryTree.BFS.T5_0429;

import Ep06_BinaryTree.Node;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Mine {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new LinkedList<>();
        Deque<Node> deque = new LinkedList<>();

        if (root == null) return res;

        deque.offer(root);
        while(!deque.isEmpty()){
            int size = deque.size();
            List<Integer> tempList = new LinkedList<>();
            while (size > 0){
                size--;     // 要把size--循环控制步骤放在continue之前执行，以免被越过
                Node tempNode = deque.poll();
                tempList.add(tempNode.val);

                List<Node> children = tempNode.children;
                if (children == null || children.size() == 0){
                    continue;
                }
                for (Node ch: children) {
                    // 上面只是判断了children这个list是否存在，但是没有判断list中是否有null值
                    // 因此还要再加一层判断
                    if (ch != null){
                        deque.offer(ch);
                    }
                }
            }
            res.add(tempList);
        }
        return res;
    }
}
